package com.team.childapp.ui.login

import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.team.childapp.R
import com.team.childapp.base.App
import com.team.childapp.base.activity.BaseActivity
import com.team.childapp.base.listener.ICallBackResultListener
import com.team.childapp.bean.login.LoginBean
import com.team.childapp.config.BaseConfig
import com.team.childapp.databinding.ActivityRegisterBinding
import com.team.childapp.http.LoginLogical
import com.team.childapp.ui.MainActivity
import com.team.childapp.ui.setting.SettingInformationActivity


/**
 * Create on: 2024/12/25
 * by Mr.Zhu
 * Description: 注册页面
 */
class RegisterActivity: BaseActivity<ActivityRegisterBinding>(R.layout.activity_register) {
    override fun initData() {
        mBinding.shopEd.setOnEditorActionListener { textView, actionId, keyEvent ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
               changeVerView()
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(textView.windowToken, 0)
                true
            } else{
                false
            }
        }
        mBinding.signLayout.setOnClickListener {
            if (mBinding.phoneLayout.visibility == android.view.View.VISIBLE) {
                val phone = mBinding.shopEd.text.toString()
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                LoginLogical.getInstanceLogin().requestVerifyCode(this,phone,
                    object : ICallBackResultListener {
                        override fun onCallBack(result: Any?) {
                            changeVerView()
                        }
                    })
            } else {
                onLogin()
            }

        }
        mBinding.registerVerifyEdittext1.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                mBinding.registerVerifyEdittext2.requestFocus()
            }

            override fun afterTextChanged(s: Editable) {}
        })
        mBinding.registerVerifyEdittext2.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                mBinding.registerVerifyEdittext3.requestFocus()
            }

            override fun afterTextChanged(s: Editable) {}
        })
        mBinding.registerVerifyEdittext3.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                mBinding.registerVerifyEdittext4.requestFocus()
            }

            override fun afterTextChanged(s: Editable) {}
        })
        mBinding.registerVerifyEdittext4.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                onLogin()
            }

            override fun afterTextChanged(s: Editable) {}
        })
        mBinding.registerVerifyEdittext4.setOnEditorActionListener { textView, actionId, keyEvent ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                onLogin()
                //隐藏软键盘
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(textView.windowToken, 0)
                true
            } else{
                false
            }
        }
    }

    private fun onLogin() {
        val num1 = mBinding.registerVerifyEdittext1.text.toString()
        val num2 = mBinding.registerVerifyEdittext2.text.toString()
        val num3 = mBinding.registerVerifyEdittext3.text.toString()
        val num4 = mBinding.registerVerifyEdittext4.text.toString()
        if (TextUtils.isEmpty(num1) || TextUtils.isEmpty(num2) || TextUtils.isEmpty(num3) || TextUtils.isEmpty(num4)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show()
            return
        }
        val verifyCode = num1 + num2 + num3 + num4
        LoginLogical.getInstanceLogin().requestUserLogin(this,mBinding.shopEd.text.toString(),verifyCode,
            object : ICallBackResultListener {
                override fun onCallBack(result: Any?) {
                    if (result == null) {
                        return
                    }
                    val userInfo = result as LoginBean
                    App.application().getShareData().putString(BaseConfig.TOKEN_ID,userInfo.getAccess_token())
                    App.application().getShareData().putInt(BaseConfig.HAS_LOGIN,userInfo.getUserStatus())
                    App.application().getShareData().putString(BaseConfig.USER_ID,userInfo.userId)
                    if (userInfo.sex != null) {
                        App.application().getShareData().putInt(BaseConfig.USER_SEX,userInfo.getSex())
                    }
                    loginSuccess()
                }
            })
    }
    private fun changeVerView(){
        mBinding.phoneLayout.animate()
            .alpha(0f)
            .setDuration(300)
            .withEndAction{
                mBinding.phoneLayout.visibility = android.view.View.INVISIBLE
                mBinding.registerPhoneTv.visibility = android.view.View.INVISIBLE
                mBinding.loginLayout.visibility = android.view.View.VISIBLE
                mBinding.phoneLayout.alpha = 0f
                mBinding.phoneLayout.animate()
                    .alpha(1f)
                    .setDuration(300) // 动画持续时间，单位为毫秒
            }
        mBinding.registerVerifyEdittext1.requestFocus()
        // 延迟显示软键盘
        Handler(Looper.getMainLooper()).postDelayed({
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(mBinding.registerVerifyEdittext1, InputMethodManager.SHOW_IMPLICIT)
        }, 100) // 延迟 100 毫秒
    }

    private fun loginSuccess(){
        val hasLogin = App.application().getShareData().getInt(BaseConfig.HAS_LOGIN)
        if (hasLogin==0) {//
//            App.application().getShareData().putBoolean(BaseConfig.HAS_LOGIN,true)
            start<MainActivity>()
        } else {
            start<SettingInformationActivity>()
        }
        finish()
    }

}